package com.youtellv1.controller;

import com.github.pagehelper.PageInfo;
import com.youtellv1.config.ResultData;
import com.youtellv1.entity.Child;
import com.youtellv1.service.ChildService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/manager/child")
public class ChildController {
    @Autowired
    private ChildService childService;

    @GetMapping("/list")
    public ResultData<PageInfo<Child>> list(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "8") int size) {
        try {
            PageInfo<Child> pageInfo = childService.findChildByPage(page, size);
            return new ResultData<>(pageInfo);
        } catch (Exception e) {
            return new ResultData<>(500, "分页获取失败：" + e.getMessage(), null);
        }
    }

    @PostMapping("/save")
    public ResultData<Void> save(
            @RequestParam("cname") String cname,
            @RequestParam("csex") String csex,
            @RequestParam("cage") Integer cage,
            @RequestParam("cparent") String cparent,
            @RequestParam("ctel") String ctel,
            @RequestParam("flag") String flag
    ) {
        try {
            Child child = new Child();
            child.setCname(cname);
            child.setCsex(csex);
            child.setCage(cage);
            child.setCparnt(cparent);
            child.setCtel(ctel);
            child.setFlag(flag);
            childService.saveService(child);
            return new ResultData<>(200, "添加成功", null);
        } catch (Exception e) {
            return new ResultData<>(500, "保存学生信息失败 : " + e.getMessage(), null);
        }
    }

    @PostMapping("/leave")
    @ResponseBody
    public ResultData<Void> leave(@RequestParam("cid") Integer cid) {
        try {
            childService.updateFlagService(cid, "0");
            return new ResultData<>(200, "退学成功", null);
        } catch (Exception e) {
            return new ResultData<>(500, "退学失败: " + e.getMessage(), null);
        }
    }

    @PostMapping("/reEnroll")
    @ResponseBody
    public ResultData<Void> reEnroll(@RequestParam("cid") Integer cid) {
        try {
            childService.updateFlagService(cid, "1");
            return new ResultData<>(200, "重新入学成功", null);
        } catch (Exception e) {
            return new ResultData<>(500, "重新入学失败: " + e.getMessage(), null);
        }
    }

    @PostMapping("/update")
    public ResultData<Void> updateChild(@RequestBody Child child) {
        try {
            childService.updateService(child);
            return new ResultData<>();
        } catch (Exception e) {
            return new ResultData<>(500, "更新失败: " + e.getMessage(), null);
        }
    }

}
